package cn.com.ccxe.web;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.com.ccxe.core.entity.Article;
import cn.com.ccxe.core.entity.Keyword;
import cn.com.ccxe.core.entity.Website;
import cn.com.ccxe.core.search.Searcher;
import cn.com.ccxe.core.util.Tool;
import cn.com.ccxe.dao.OperationStatus;
import cn.com.ccxe.service.FavoriteBussiness;
import cn.com.ccxe.service.WebsiteBussiness;
import cn.com.ccxe.web.form.WebsiteActionForm;

import com.ccxe.manage.service.CurrUserInfo;

public class CustomerMonitorAction extends BasciAction {

	private static final long serialVersionUID = 8498343677925536129L;
	private static final Logger logger = LoggerFactory.getLogger(CustomerMonitorAction.class);
	private static WebsiteBussiness bussiness = new WebsiteBussiness();
	private static String PATH = "/zebra/customer/module/customerMonitorAction";
	@SuppressWarnings("unused")
	private static int MAX_THRESHOLD = 50; //每次获取文章的最大数量
	
	@Override
	protected void dispatch(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		WebsiteActionForm actionForm = new WebsiteActionForm(req);
		// 请求的方法
		String method = actionForm.getMethod();
		if (isEmpty(method)) {
			method = method.trim();
		}
		CurrUserInfo userInfo = actionForm.getUserInfo();
		if (userInfo == null) {
			logger.info("用户信息已过期，请重新登录！");
			resp.sendRedirect("/login.jsp");
			invalidateSession(req);
			return;
		}
		if (!isEmpty(method)) {
			show(req, resp, actionForm);
			return;
		}
		if ("show".equals(method)) {
			show(req, resp, actionForm);
			return;
		}
		if ("back".equals(method)) {
			back(req, resp, actionForm);
			return;
		}
		if ("toArticle".equals(method)) {
			toArticle(req, resp, actionForm);
			return;
		}
		if ("toSelectKeyword".equals(method)) {
			toSelectKeyword(req, resp, actionForm);
			return;
		}
		if ("search".equals(method)) {
			search(req, resp, actionForm);
			return;
		}
		if ("addFavoriteKeyword".equals(method)) {
			addFavoriteKeyword(req, resp, actionForm);
			return;
		}
		if ("delFavoriteKeyword".equals(method)) {
			delFavoriteKeyword(req, resp, actionForm);
			return;
		}

	}

	private boolean isEmpty(String method) {
		return !StringUtils.isEmpty(method);
	}

	private void show(HttpServletRequest req, HttpServletResponse resp,
			WebsiteActionForm actionForm) throws ServletException, IOException {

		int id = actionForm.getId();
		List<Website> moduleList = null;
		if (id <= 0) {
			moduleList = bussiness.getTopWebsite();
		} else {
			Website parent = bussiness.get(id);
			if (parent == null) {
				parent = new Website(id);
			}
			moduleList = bussiness.getChildWebsite(id);
			req.setAttribute("parentModule", parent);
		}
		req.setAttribute("moduleList", moduleList);
		forward(req, resp, "/zebra/customer/module/show.jsp");
	}

	private void back(HttpServletRequest req, HttpServletResponse resp,
			WebsiteActionForm actionForm) throws ServletException, IOException {
		// 返回的应该为父模块的父模块下面的子模块信息。
		int id = actionForm.getParentId();
		int parentId = bussiness.getParentWebsiteId(id);
		StringBuilder path = new StringBuilder(PATH);
		path.append("?method=show&id=").append(parentId);
		logger.info("PATH:" + path.toString());
		resp.sendRedirect(path.toString());
	}
	
	private void toArticle(HttpServletRequest req, HttpServletResponse resp,
			WebsiteActionForm actionForm) throws ServletException, IOException {
		String url = actionForm.getPath();
		String mirrorPath = Tool.getMirrorFileByUrl(url);
		
		if(!StringUtils.isEmpty(mirrorPath)) {
			req.setAttribute("mirrorPath", mirrorPath);
		}
		else {
			req.setAttribute("url", url);
		}
		forward(req, resp, "/zebra/customer/module/showPage.jsp");
	}
	private void toSelectKeyword(HttpServletRequest req, HttpServletResponse resp,
			WebsiteActionForm actionForm) throws ServletException, IOException {
		
		int moduleId = actionForm.getModuleId();
		String userId = actionForm.getUserInfo().getUserId();
		//所有被选中的KEYWORD
		FavoriteBussiness bussiness = new FavoriteBussiness();
		List<Keyword> selectedKeywordList= bussiness.getSelectedKeywordList(moduleId,userId);
		req.setAttribute("selectedKeywordList", selectedKeywordList);
		//所有未被选中的keyword
		List<Keyword> notSelectedKeywordList= bussiness.getNotSelectedKeywordList(moduleId,userId);
		req.setAttribute("notSelectedKeywordList", notSelectedKeywordList);
		req.setAttribute("args", actionForm);
		
		forward(req, resp, "/zebra/customer/module/keywordList.jsp");
	}
	
	private void addFavoriteKeyword(HttpServletRequest req,
			   HttpServletResponse resp, 
			   WebsiteActionForm actionForm)
			throws ServletException,
			   	   IOException {
		FavoriteBussiness bussiness = new FavoriteBussiness();
		OperationStatus status = bussiness.addFavoriteKeyword(
										actionForm.getKeywordId(), 
										actionForm.getModuleId(), 
										actionForm.getUserInfo().getUserId());
		switch (status) {
		case SUCCESS:
			StringBuilder sb = new StringBuilder();
			sb.append(PATH).append("?method=toSelectKeyword&moduleId=")
						   .append(actionForm.getModuleId());
			forward(req, resp,sb.toString());
			break;
		default:
			error(req, resp, "添加操作失败，请确认操作步骤是否正确！");
			break;
		}
	}
	
	private void delFavoriteKeyword(HttpServletRequest req, 
			 HttpServletResponse resp, 
			 WebsiteActionForm actionForm)
		throws ServletException,
			   IOException {
	FavoriteBussiness fwb = new FavoriteBussiness();
	OperationStatus status = fwb.delFavoriteKeyword(
			actionForm.getKeywordId(), 
			actionForm.getModuleId(), 
			actionForm.getUserInfo().getUserId());
	
	switch (status) {
	case SUCCESS:
		StringBuilder sb = new StringBuilder();
		sb.append(PATH).append("?method=toSelectKeyword&moduleId=")
					   .append(actionForm.getModuleId());
		forward(req, resp,sb.toString());
		break;
	default:
		error(req, resp, "删除操作失败，请确认操作步骤是否正确！");
		break;
	}
}
	
	private void search(HttpServletRequest req, HttpServletResponse resp,
			WebsiteActionForm actionForm) throws ServletException, IOException {
		int moduleId = actionForm.getId();
		String userId = actionForm.getUserInfo().getUserId();
		//所有被选中的KEYWORD
		FavoriteBussiness bussiness = new FavoriteBussiness();
		List<Keyword> list= bussiness.getSelectedKeywordList(moduleId,userId);
		Searcher searcher = Searcher.getInstance();
//		List<Article> articleList = searcher.search(keywords, actionForm.getModuleId());
		List<Article> articleList = searcher.search(list, moduleId);
		req.setAttribute("articleList", articleList);
		forward(req, resp, "/zebra/customer/module/articleList.jsp");
	}
	
}
